package com.hzhq.contract.convert.method;

import cn.hutool.core.collection.CollUtil;

import java.io.File;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: hzhq1255
 * @Mail: hzhq1255@163.com
 * @Date: 2021/5/10 5:11 下午
 * @Desc:
 */
public class AttachmentConvertMethod {

    public static final long UNIT_NUM = 1024L;
    public static final int RETAIN_DECIMAL = 2;
    public static final HashMap<Integer, String> UNIT_MAP = CollUtil.newHashMap();
    static {
        UNIT_MAP.put(1,"B");
        UNIT_MAP.put(2,"KB");
        UNIT_MAP.put(3,"MB");
        UNIT_MAP.put(4,"GB");
        UNIT_MAP.put(5,"TB");
    }
    public static final HashMap<String, String> FILE_TYPE_MAP = CollUtil.newHashMap();
    static {
        FILE_TYPE_MAP.put("","未知文件");
        FILE_TYPE_MAP.put("txt","文本文件");
        FILE_TYPE_MAP.put("pdf","pdf文件");
        FILE_TYPE_MAP.put("doc","word文档");
        FILE_TYPE_MAP.put("docx","word文档");
        FILE_TYPE_MAP.put("xls","excel表格");
        FILE_TYPE_MAP.put("xlsx","excel表格");
        FILE_TYPE_MAP.put("ppt","ppt演示文件");
        FILE_TYPE_MAP.put("pptx","ppt演示文件");
        FILE_TYPE_MAP.put("png","png图片");
        FILE_TYPE_MAP.put("jpg","jpg图片");
        FILE_TYPE_MAP.put("jpeg","jpeg图片");
        FILE_TYPE_MAP.put("bmp","bmp图片");
    }

    public static String fileSizeToString(long size){
        double value = (double) size;
        int count = 1;
        while (value > UNIT_NUM){
            value = value / UNIT_NUM;
            count++;
        }
        return new BigDecimal(value).setScale(RETAIN_DECIMAL,RoundingMode.HALF_UP) + UNIT_MAP.get(count);
    }

    public static String getAttachTypeByAttachName(String attachName){
        int index = attachName.lastIndexOf('.');
        if (index == -1){
            return FILE_TYPE_MAP.get("");
        }
        String fileType = attachName.substring(index + 1);
        for (String key: FILE_TYPE_MAP.keySet()){
            if (key.equals(fileType)){
                return FILE_TYPE_MAP.get(fileType);
            }
        }
        return FILE_TYPE_MAP.get("");
    }

    public static void main(String[] args) {
        //acceptType: 'image/*,.pdf,.txt,.docx,.doc,.xls,.xlsx,.ppt,.pptx',
        String test1 = "a.nihao.txt";
        String test2 = "nihao";
        int index1 = test1.lastIndexOf('.');
        int index2 = test2.lastIndexOf('.');
        System.out.println(getAttachTypeByAttachName(test2));
    }
}
